import { LayoutAnimation, Vibration, Linking } from 'react-native'
import * as ImagePicker from 'expo-image-picker';
import * as ExpoRouter from 'expo-router'
import { requestLog } from '../http/Request'
import _ from './BaseTools'
import IP from '../http/host'

/**
 * ! 1. API
 * ! 2. 页面逻辑
 * ! 3. 公共UI
 */
const APIUtils = {
    // ! API 工具类：页面跳转、自定义API
    requestLog: (data) => requestLog(IP.server_ip, data),
    ExpoRouter,

    /**
     *  * 布局移动动画
     * @returns void
     */
    moveAnimate: () => LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut),

    openURL: async (url, msg) => {
        const [err, res] = await _.to(Linking.canOpenURL(url))
        if (err) return Utils.showInfo(msg || '跳转失败~')
        Linking.openURL(url)
    },

    /**
     * * 震动
     * @param {number} time 时间
     * @param {boolean} repeat 重复
     * @returns void
     */
    vibration: (time, repeat = false) => Vibration.vibrate(time, repeat),

    /**
     * * 取消震动
     * @returns void
     */
    cancelVibration: () => Vibration.cancel(),

    /**
     * * 选择相册图片
     * @param {object} config 配置
     * @returns {string}
     */
    pickImage: async (config = {}) => {
        // 请求相册权限
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync()
        if (status !== 'granted') {
            return [{ message: 'APP 获取相册权限失败~' }, undefined]
        }
        config = {
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            quality: 1,
            exif: true,
            base64: true,
            ...config,
        }
        // 选择图片
        let result = await ImagePicker.launchImageLibraryAsync(config);
        if (result.canceled) {
            return [{ message: '' }, undefined]
        }
        // 多张
        if (config.allowsMultipleSelection) return [undefined, result?.assets]
        // 单张
        return [undefined, result?.assets[0]]
    }
}

export default APIUtils
